package com.alinesno.cloud.initializr.starter.cicd.deploy.k8s.api;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.initializr.starter.cicd.deploy.k8s.BaseApi;
import com.alinesno.cloud.initializr.starter.cicd.deploy.k8s.bean.ServiceBean;

import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;

/**
 * k8s容器发布
 * 
 * @author WeiXiaoJin
 * @date 2021年6月25日 下午8:23:57
 */
@Component
public class ServiceApi extends BaseApi {
	
	private static final Logger log = LoggerFactory.getLogger(ServiceApi.class) ; 

	/**
	 * 添加Service
	 * @return 
	 */
	public Service createService(ServiceBean bean) {
		
		String namespace = bean.getNamespace() ; 
		String serviceName = bean.getServiceName() ; 
		int port = bean.getPort() ; 
		int targetPort = bean.getTargetPort() ;
		String selecterApp = bean.getSelecterApp() ; 
		
		Assert.hasLength(namespace , "命名空间为空.");
		Assert.hasLength(serviceName , "服务名称为空.");
		Assert.hasLength(selecterApp , "关联服务名称为空.");
		Assert.isTrue(port > 0 , "端口不能为空.");
		Assert.isTrue(targetPort> 0 , "目标端口不能为空.");
		
		Map<String , String> labelMap = new HashMap<String , String>() ;
		labelMap.put("app", serviceName) ; 
		
		Map<String , String> selectMap = new HashMap<String , String>() ;
		selectMap.put("app", serviceName) ; 
	
		Service service = new ServiceBuilder()
		    .withApiVersion("v1")
		    .withKind("Service")
		   
		    // >>>>>>>>>>> metadata_start >>>>>>>>>>>>>>>>>
			.withNewMetadata()
			.withName(serviceName)
			.withNamespace(namespace)
			.withLabels(labelMap)
			.endMetadata()
		    // >>>>>>>>>>> metadata_end >>>>>>>>>>>>>>>>>
			
			.withNewSpec()
			.withSelector(Collections.singletonMap("app", selecterApp))
			.addNewPort()
			.withName(serviceName)
			.withProtocol("TCP")
			.withPort(port)
			.withTargetPort(new IntOrString(targetPort))
			.endPort()
			.withType("ClusterIP")
			.withSelector(selectMap)
			.endSpec()
			
			.build();

		service = client().services().inNamespace(namespace).create(service);
		log.info("Created service with name {}", service.getMetadata().getName());
		  
		return service ; 
	}

	
}
